<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/9 0009
 * Time: 13:49
 */

namespace logic\yuding\driver;

use logic\LogicException;
use mod\Travel;
use mod\Lianpiao;
use mod\Zuhe;
use mod\DynamicPrize;
use mod\Pihao;
use mod\Yuding;

abstract class Base
{
    //出错提示信息 根据source不同提示不同内容
    public $msg = array();
    //数据信息 如果是激活操作来自表单 如果是repare操作来源lianpiao表
    public $data = array();
    //操作来源 pc/mobile/admin
    public $source = "";
    //来源显示信息 2.0网站前台 微信公众平台 2.0网站后台
    public $sourceMsg = '';
    //lianpiao表查询结果集
    public $lianpiaoResult = array();
    //travel表查询结果集
    public $travelResult = array();
    //yuding表查询结果集
    public $yudingResult = array();
    //pihao表查询结果集
    public $pihaoResult = array();
    //session->user  结果集合
    public $userInfo = array();
    //订单操作id
    public $operaId = 0;
    /*
     * 操作model
     */
    public $lianpiaoModel = null;
    public $travelModel = null;
    public $dynamicPrizeModel = null;
    public $zuheModel = null;
    public $pihaoModel = null;
    public $yudingModel = null;

    /*
     * 清楚所有全局数据
     */
    public function clear(){
	    $this->msg = array();
	    $this->data = array();
	    $this->source = "";
	    $this->sourceMsg = '';
	    $this->lianpiaoResult = array();
	    $this->travelResult = array();
	    $this->yudingResult = array();
	    $this->pihaoResult = array();
	    $this->userInfo = array();
	    $this->operaId = 0;
    }

    /**
     * 设置来源接口
     * @param $source
     * 'pc' => '2.0网站前台',
     * 'mobile' => '微信公众平台',
     * 'admin' => '2.0网站后台',
     */
    public function setSource($source)
    {
        $this->source = $source;
        $this->setMsg();
    }

    /**
     * 设置数据信息接口
     * @param array $data
     */
    public function setData($data = array())
    {
        $this->data = $data;
    }

    /**
     * 操作用户信息接口
     * @param $userInfo
     */
    public function setUserInfo($userInfo)
    {
        $this->userInfo = $userInfo;
    }

    /*
     * 操作订单id
     */
    public function setOperaId( $operaId ){
    	$this->operaId = $operaId;
    }

    /**
     * 设置出错提示信息接口 根据source
     */
    public function setMsg()
    {
        $errorMsg = [
            'pc' => [
                'isjihuo' => '该联票未被激活',
                'issuo' => '该联票已经被锁定',
                'isyuding' => '该联票已经预定过了',
                'iskaitong' => '该联票未开通,请与销售方联系!',
                'shiyongdate' => '出游时间超过该联票的最终使用时间，请重新选择游玩时间!',
                'zuhesp' => "请在开放时间内选择，开放时间为：#starttime#~#endtime#",
                'suoding' => '该景区暂停营业,不能预订!',
                'jqkfshiduan' => '该景区当天不开放，请选择其它日期',
                'maxnums' => '当天预定已满，请选择其他日期',
                'isclose' => '#lianpiaono#该联票已经预定过了',
                'is_suoding' => '当前产品已经暂停预订，请联系客服！',
                'jqcloseday' => '景区当天不开放，请重新选择游玩日期！',
                'timeswitch' => '出游需提前预约，当天预约不予受理,请重新选择出游时间！',
                'tqtime' => '游览前须至少提前#tqtime#小时预约，未预约直接到景区无效！',
            ],
            'mobile' => [
                'isjihuo' => '该联票未被激活',
                'issuo' => '该联票已经被锁定',
                'isyuding' => '该联票已经预定过了',
                'iskaitong' => '该联票未开通,请与销售方联系!',
                'shiyongdate' => '出游时间超过该联票的最终使用时间，请重新选择游玩时间!',
                'zuhesp' => "请在开放时间内选择，开放时间为：#starttime#~#endtime#",
                'suoding' => '该景区暂停营业,不能预订!',
                'jqkfshiduan' => '该景区当天不开放，请选择其它日期',
                'maxnums' => '当天预定已满，请选择其他日期',
                'isclose' => '#lianpiaono#该联票已经预定过了',
                'is_suoding' => '当前产品已经暂停预订，请联系客服！',
                'jqcloseday' => '景区当天不开放，请重新选择游玩日期！',
                'timeswitch' => '出游需提前预约，当天预约不予受理,请重新选择出游时间！',
                'tqtime' => '游览前须至少提前#tqtime#小时预约，未预约直接到景区无效！',
            ],
            'admin' => [
                'isjihuo' => '该联票未被激活',
                'issuo' => '该联票已经被锁定',
                'isyuding' => '该联票已经预定过了',
                'iskaitong' => '该联票未开通,请与销售方联系!',
                'shiyongdate' => '出游时间超过该联票的最终使用时间，请重新选择游玩时间!',
                'zuhesp' => "请在开放时间内选择，开放时间为：#starttime#~#endtime#",
                'suoding' => '该景区暂停营业,不能预订!',
                'jqkfshiduan' => '该景区当天不开放，请选择其它日期',
                'maxnums' => '当天预定已满，请选择其他日期',
                'isclose' => '#lianpiaono#该联票已经预定过了',
                'is_suoding' => '当前产品已经暂停预订，请联系客服！',
                'jqcloseday' => '景区当天不开放，请重新选择游玩日期！',
                'timeswitch' => '出游需提前预约，当天预约不予受理,请重新选择出游时间！',
                'tqtime' => '游览前须至少提前#tqtime#小时预约，未预约直接到景区无效！',
            ],
        ];
        $this->msg = $errorMsg[$this->source];

        $sourceMsg = [
            'pc' => '2.0网站前台',
            'mobile' => '微信公众平台',
            'admin' => '2.0网站后台',
        ];
        $this->sourceMsg = $sourceMsg[$this->source];
    }

	/**
	 * 获取联票信息集合，验证票号是否存在
	 */
    public function getLianpiao()
    {
    	//兼容目前业务的查询条件
	    !empty($this->data['lianpiaono']) && $where=array('lianpiaono'=>$this->data['lianpiaono']);
	    !empty($this->data['lianpiao_id']) && $where=array('id'=>$this->data['lianpiao_id']);
	    $this->lianpiaoModel = new Lianpiao();
        $this->lianpiaoResult = $this->lianpiaoModel->where($where)->find();
        if (empty($this->lianpiaoResult)) {
            throw new LogicException("联票号不存在！");
        }
    }

    /*
     * 检查联票的基本属性，是否符合条件
     */
    public function checkLianpiao()
    {
        empty($this->lianpiaoResult) && $this->getLianpiao();

        if ($this->lianpiaoResult['isjihuo'] != 10) {
            throw new LogicException($this->msg['isjihuo']);
        }
        if ($this->lianpiaoResult['issuo'] == 10) {
            throw new LogicException($this->msg['issuo']);
        }
        if ($this->lianpiaoResult['iskaitong'] == 1) {
            throw new LogicException($this->msg['iskaitong']);
        }
        if (strtotime($this->data['date_str'])>strtotime($this->lianpiaoResult['shiyongdate'])) {
            throw new LogicException($this->msg['shiyongdate']);
        }
    }

    /*
     * 检查出游日期是否在产品组合中对应景区的开放时间之内
     */
    public function checkZuhesp()
    {
        empty($this->lianpiaoResult) && $this->getLianpiao();

        $this->dynamicPrizeModel = new DynamicPrize();
        $ktime = $this->dynamicPrizeModel
	        ->field('starttime,endtime')
            ->where("prize_coupon_code", $this->data['prize_coupon_code'])
            ->find();
        if(strtotime(trim ($this->data['date_str']))<strtotime($ktime['starttime'])||strtotime(trim ($this->data['date_str']))>strtotime($ktime['endtime'])){
            throw new LogicException(str_replace(['#starttime#', '#endtime#'], [$ktime['starttime'], $ktime['endtime']], $this->msg['zuhesp']));
        }
    }

    /*
     * 获取订单表model
     */
    public function getYuding(){
    	$this->yudingModel = new Yuding();
    }

    /*
     * 获取景区表信息集合
     */
    public function getTravel()
    {
    	$this->travelModel = new Travel();
        $this->travelResult = $this->travelModel->find($this->data['jqid']);
    }

    /*
     * 检查景区各项开关设置状态
     */
    public function checkTravel()
    {
        empty($this->travelResult) && $this->getTravel();
        empty($this->yudingModel)  && $this->getYuding();

        //判断景区是否处于锁定状态，锁定状态下，景区不可以预定
        switch ($this->source) {
            case "pc" :
                if ($this->travelResult['qiantaisuoding'] == 1) {
                    throw new LogicException($this->msg['suoding']);
                }
                break;
            case "mobile" :
                if ($this->travelResult['mobilesd'] == 1) {
                    throw new LogicException($this->msg['suoding']);
                }
                break;
            case "admin" :
                if ($this->travelResult['htsuoding'] == 1) {
                    throw new LogicException($this->msg['suoding']);
                }
                break;
        }

        // 判断出游时间是否处于该景区的关闭时段，关闭时段下不可以预定
        $stime = strtotime($this->data['date_str']);
        if (!empty($this->travelResult['jqkfshiduan'])) {
            $shutimearr=explode('|', $this->travelResult['jqkfshiduan']);

            if (count($shutimearr)>=1) {
                foreach ($shutimearr as $v) {
                    $vv=explode('--', $v);
                    if ($stime>strtotime($vv[0]) and $stime<strtotime($vv[1])) {
                        throw new LogicException($this->msg['jqkfshiduan']);
                    }
                }
            }
        }
		//判断景区当天预订量是否达到最大预订设置值
        $maxnums = $this->travelResult['maxnums'];
        if ($maxnums > 0) {
            /**
             * yuding datediff引起索引失效 大表全表扫描 性能问题
             */
            $counts = $this->yudingModel
                ->where("travel_id", $this->data['jqid'])
                ->where("datediff(yudingtime,'{$this->data['date_str']}')=0")
                ->where("isclose", 0)
                ->count();
            if ($counts >= $maxnums) {
                throw new LogicException($this->msg['maxnums']);
            }
        }
    }

    /*
     * 获取pihao信息集合
     */
    public function getPihao()
    {
        empty($this->lianpiaoResult) && $this->getLianpiao();
		$this->pihaoModel = new Pihao();
        $this->pihaoResult = $this->pihaoModel->find($this->lianpiaoResult['pihao_id'] );
    }

    /*
     * 检查批号是否锁定，和批号的关闭时段是否设置
     */
    public function checkPihao()
    {
        empty($this->pihaoResult) && $this->getPihao();
		//检查批号是否锁定
        if ($this->pihaoResult['is_suoding'] == 0) {
            throw new LogicException($this->msg['is_suoding']);
        }

    }

    /*
     * 批号提前预订时间限制检查
     * 景区信息集合中：
     *       timeswitch 等于 0   判断批号的提前预订时间量
     *       timeswitch 等于 1   判断景区的提前预订时间量
     *
     */
    public function checkPihaoTime()
    {
	    empty($this->travelResult) && $this->getTravel();
        empty($this->pihaoResult) && $this->getPihao();
		//预订日期必须是当天之后的时间
	    if( strtotime($this->data['date_str']) - strtotime(date('Y-m-d',time())) < 0 ){
		    throw new LogicException('出游日期有误，不能预定当天以前日期！');
	    }

        if($this->travelResult['timeswitch']==0){
	    	//批号中的设置不能预订当天的
            if (get_daynum(date('Y-m-d',time()), $this->data['date_str']) == 0) {
                throw new LogicException($this->msg['timeswitch']);
            }
            if (strtotime($this->data['date_str'])-time() < $this->pihaoResult['tqtime'] * 3600) {
                throw new LogicException(str_replace('#tqtime#', $this->pihaoResult['tqtime'], $this->msg['tqtime']));
            }
        }else if($this->travelResult['timeswitch']==1){
            if( $this->travelResult['tqtime'] > 0 ){
                if ( strtotime($this->data['date_str'])-time() < $this->travelResult['tqtime'] * 3600 ) {
                    throw new LogicException(str_replace('#tqtime#', $this->travelResult['tqtime'], $this->msg['tqtime']));
                }
            }
        }
    }

    /*
     * 检查订单是否在库中是否存在
     *      已经取消的订单更新isclose标志位为0
     *      新订单插入库中
     * return $data  订单数组
     * 设置操作poreaid
     */
    public function checkYuding()
    {
        empty($this->lianpiaoResult) && $this->getLianpiao();
        empty($this->yudingModel) && $this->getYuding();

        $this->yudingResult = $this->yudingModel
            ->where("prize_coupon_code", $this->data['prize_coupon_code'])
            ->find();
        //预订过不能重复下单
        if(!empty($this->yudingResult) && $this->yudingResult['isclose']==0){
            throw new LogicException(str_replace('#lianpiaono#', $this->lianpiaoResult['lianpiaono'], $this->msg['isclose']));
        }
		//封装数据和操作标志
        $yuding = $this->formatYuding();
        if(empty($this->yudingResult)){
	        return array('flag'=>'insert','data'=>$yuding);
        }
        if($this->yudingResult['isclose'] == 1){
	        $this->setOperaId( $this->yudingResult['id'] );
        	$yuding['isclose'] = 0;
	        return array('flag'=>'update','data'=>$yuding);
        }

    }

    /*
     * 订单数据封装并返回
     */
    public function formatYuding()
    {
	    empty($this->lianpiaoResult) && $this->getLianpiao();
	    empty($this->travelResult) && $this->getTravel();

        $data = array();
        //子景区预定判断
	    $data ['uid']                = $this->lianpiaoResult['uid'];
        $data ['lianpiao_id']       = $this->lianpiaoResult['id'];
	    $data ['lianpiaono']        = $this->lianpiaoResult['lianpiaono'];
        $data ['yudingtime']        = $this->data['date_str'];
        $data ['endyudingtime']     = $this->data['date_str'];
	    $data ['jqname']            = $this->travelResult['title'];
	    $data ['travel_id']         = $this->data['jqid'];
	    $data ['worker']            = $this->lianpiaoResult['username'];
	    $data ['phone']             = $this->lianpiaoResult['phone'];
	    $data ['shenfenzheng']      = $this->lianpiaoResult['shenfenid'];
	    $data ['yudingrenid']       = $this->userInfo['uid'];
	    $data ['yudingrenname']     = $this->userInfo['nickname'];
        $data ['zuhe_id']           = $this->lianpiaoResult['zuhe_id'];
        $data ['pihao_id']          = $this->lianpiaoResult['pihao_id'];
	    $data ['com_id']            = $this->lianpiaoResult['com_id'];
	    $data ['prize_coupon_code']= $this->data['prize_coupon_code'];
	    $data ['addtime']           = date ( 'Y-m-d H:i:s' );
        return $data;
    }



}